package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.ex.CustomerException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ghy
 * @version v1.0
 * create on 2022/11/18 12:01
 */
@Service
@Slf4j
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public R findList(Category category) {
        //where type = ?
        LambdaQueryWrapper<Category> lqw = Wrappers.<Category>lambdaQuery()
                .eq(category.getType() != null, Category::getType, category.getType());
        //order by sort asc
        lqw.orderByAsc(Category::getSort);
        List<Category> categories = this.list(lqw);
        return R.success(categories);
    }

    @Override
    public R deleteById(Long id) {

        //1.查询当前分类ID有没有被菜品表关联？
        //select count(*) from dish where category_id = ?
        int count = dishService.count(Wrappers.<Dish>lambdaQuery().eq(Dish::getCategoryId, id));
        if(count > 0) {
            //1.1 有，不能删除：抛出异常
            throw new CustomerException("当前分类有关联的菜品数据，不能删除！");
        }

        //2.查询当前分类ID有没有被套餐表关联？
        int count2 = setmealService.count(Wrappers.<Setmeal>lambdaQuery().eq(Setmeal::getCategoryId, id));
        if(count2 > 0) {
            //2.1 有，不能删除：抛出异常
            throw new CustomerException("当前分类有关联的套餐数据，不能删除！");
        }
        //3.可以删除，根据ID删除
        this.removeById(id);

        return R.success("分类删除成功");
    }

    @Override
    public R modify(Category category) {
        //1.判断当前分类名称在数据库是否存在？
        Category dbCategory = this.getOne(Wrappers.<Category>lambdaQuery().eq(Category::getName, category.getName()));
        if(dbCategory == null || dbCategory.getId().equals(category.getId())) {
            this.updateById(category);
        } else {
            throw new CustomerException("当前分类名称已经存在，请更换");
        }
        return R.success("分类修改成功");
    }
}
